<template>
  <view class="history">
    <!-- 导航栏 -->
    <NavBar title="浏览历史" />

    <!-- 空历史提示 -->
    <nut-empty v-if="historyList.length === 0" description="暂无浏览记录" image="empty">
      <template #footer>
        <nut-button type="primary" size="small" @click="goShopping">去逛逛</nut-button>
      </template>
    </nut-empty>

    <!-- 历史列表 -->
    <view v-else class="history-content">
      <!-- 编辑模式切换 -->
      <view class="edit-bar">
        <nut-button size="small" @click="toggleEditMode">
          {{ isEditMode ? '完成' : '管理' }}
        </nut-button>
      </view>

      <!-- 商品列表 -->
      <view class="goods-list">
        <nut-grid :column-num="2" :border="false">
          <nut-grid-item
            v-for="(item, index) in historyList"
            :key="index"
            @click="isEditMode ? toggleSelect(index) : onGoodsClick(item)"
          >
            <view class="goods-card" :class="{ 'edit-mode': isEditMode }">
              <view class="select-box" v-if="isEditMode">
                <nut-checkbox v-model="item.selected" @click.stop />
              </view>
              <image :src="item.imgUrl" style="width: 100%; height: 150px; border-radius: 4px;" />
              <view class="goods-info">
                <view class="goods-name">{{ item.name }}</view>
                <view class="price-info">
                  <nut-price :price="item.price" size="normal" />
                </view>
                <view class="view-time">{{ item.viewTime }}</view>
              </view>
            </view>
          </nut-grid-item>
        </nut-grid>
      </view>

      <!-- 底部操作栏 -->
      <view class="bottom-action" v-if="isEditMode">
        <view class="select-all">
          <nut-checkbox v-model="isAllSelected" @change="toggleSelectAll">全选</nut-checkbox>
        </view>
        <nut-button type="danger" :disabled="!hasSelectedItems" @click="removeSelected">
          删除({{ selectedCount }})
        </nut-button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import NavBar from '@/components/NavBar/index.vue'

// 编辑模式
const isEditMode = ref(false)

// 历史列表
const historyList = ref([])

// 是否全选
const isAllSelected = ref(false)

// 已选择的数量
const selectedCount = computed(() => {
  return historyList.value.filter(item => item.selected).length
})

// 是否有选中项
const hasSelectedItems = computed(() => {
  return selectedCount.value > 0
})

// 切换编辑模式
const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value
  
  // 退出编辑模式时，清除选择状态
  if (!isEditMode.value) {
    historyList.value.forEach(item => {
      item.selected = false
    })
    isAllSelected.value = false
  }
}

// 切换选择状态
const toggleSelect = (index) => {
  historyList.value[index].selected = !historyList.value[index].selected
  
  // 更新全选状态
  isAllSelected.value = historyList.value.every(item => item.selected)
}

// 切换全选状态
const toggleSelectAll = () => {
  historyList.value.forEach(item => {
    item.selected = isAllSelected.value
  })
}

// 删除选中项
const removeSelected = () => {
  Taro.showModal({
    title: '提示',
    content: '确定要删除选中的浏览记录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          // 获取选中的商品ID
          const selectedIds = historyList.value
            .filter(item => item.selected)
            .map(item => item.id)
          
          // 实际项目中应该调用API删除浏览记录
          // await api.user.removeHistory(selectedIds)
          
          // 更新列表
          historyList.value = historyList.value.filter(item => !item.selected)
          
          Taro.showToast({
            title: '删除成功',
            icon: 'success'
          })
          
          // 如果删除后列表为空，退出编辑模式
          if (historyList.value.length === 0) {
            isEditMode.value = false
          }
          
          // 更新全选状态
          isAllSelected.value = historyList.value.length > 0 && 
            historyList.value.every(item => item.selected)
        } catch (error) {
          Taro.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 点击商品
const onGoodsClick = (goods) => {
  Taro.navigateTo({
    url: `/pages/goods-details/index?id=${goods.id}`
  })
}

// 去购物
const goShopping = () => {
  Taro.switchTab({
    url: '/pages/index/index'
  })
}

// 获取浏览历史
const getHistoryList = async () => {
  try {
    // 实际项目中应该调用API获取浏览历史
    // const res = await api.user.getHistoryList()
    // historyList.value = res.map(item => ({
    //   ...item,
    //   selected: false
    // }))
    
    // 模拟数据
    setTimeout(() => {
      historyList.value = [
        {
          id: 1,
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/223778/18/6959/103158/61cc7965E6f1e0dda/a4a0450759d5614e.jpg',
          name: 'iPhone 13 Pro',
          price: '5999',
          viewTime: '2023-06-15 14:30',
          selected: false
        },
        {
          id: 2,
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/106234/8/35183/153829/63f5c4b3Fca3f0094/1f0b2a3d37496aec.jpg',
          name: '华为 Mate 50 Pro',
          price: '6299',
          viewTime: '2023-06-14 10:15',
          selected: false
        },
        {
          id: 3,
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/177161/35/30849/53503/63f5c4b3F3d9c3d5d/8db7e7e2c3d1b6c0.jpg',
          name: '小米 13 Pro',
          price: '4999',
          viewTime: '2023-06-13 16:45',
          selected: false
        },
        {
          id: 4,
          imgUrl: 'https://img14.360buyimg.com/n1/s546x546_jfs/t1/140200/32/33451/55488/63f5c4b3F1b7a9b9a/5e9b8b9b9b9b9b9b.jpg',
          name: 'OPPO Find X6 Pro',
          price: '5999',
          viewTime: '2023-06-12 09:20',
          selected: false
        }
      ]
    }, 500)
  } catch (error) {
    Taro.showToast({
      title: '获取浏览历史失败',
      icon: 'none'
    })
  }
}

// 组件挂载时初始化
onMounted(() => {
  getHistoryList()
})
</script>

<style lang="scss" scoped>
.history {
  .history-content {
    padding: 10px;
    
    .edit-bar {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 10px;
    }
    
    .goods-list {
      margin-bottom: 60px;
      
      .goods-card {
        position: relative;
        display: flex;
        flex-direction: column;
        padding: 8px;
        
        &.edit-mode {
          .select-box {
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 1;
            background-color: rgba(255, 255, 255, 0.8);
            border-radius: 50%;
            padding: 2px;
          }
        }
        
        .goods-info {
          padding: 8px 0;
          
          .goods-name {
            font-size: 14px;
            margin-bottom: 5px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
          
          .price-info {
            margin-bottom: 5px;
          }
          
          .view-time {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
    
    .bottom-action {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 15px;
      background-color: #fff;
      border-top: 1px solid #eee;
      z-index: 10;
      
      .select-all {
        display: flex;
        align-items: center;
      }
    }
  }
}
</style>